package com.adminx.service;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.adminx.dao.AccountDao;
import com.adminx.entity.Account;
import com.adminx.pojo.AccountPojo;
import com.adminx.util.PageResults;
import com.adminx.util.CodeUtil;


@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class AccountService {
	
	@Autowired
	private AccountDao accountDao;
	
	/**
	 * 通过id返回User
	 * @param id
	 * @return
	 */
	public Account info(Long accountId){
		return this.accountDao.getAccount(accountId);
	}
	
	/**
	 * 查找�?��用户
	 * @param userName
	 * @return
	 */
	public PageResults<AccountPojo> query(Integer pageIndex, Integer pageSize, String searchText){
		return this.accountDao.query(pageIndex, pageSize, searchText);
	}
	
	/**
	 * 通过ID删除账号
	 * @param accountId
	 */
	public int delBatch(String ids){
		return this.accountDao.delBatch(ids);
	}

	/**
	 * 查询菜单,返回JSON
	 * @return
	 */
	public StringBuilder getJsonMenu(){
		return this.accountDao.getJsonMenu();
	}
	
	/**
	 * 新增或修改账�?
	 * @param account
	 */
	public void save(Account account) {
		//新增
		if(account.getAccountId() == null){
			String randCode = CodeUtil.makeCode(0, 6);
			account.setRandCode(randCode);
			this.accountDao.save(account);
		}
		//修改
		else{
			Account oldAccount = this.accountDao.get(account.getAccountId());
			oldAccount.setUserName(account.getUserName());
			if(!StringUtils.isBlank(account.getPassWord())){
				oldAccount.setPassWord(new Md5PasswordEncoder().encodePassword(account.getPassWord(), oldAccount.getRandCode()));
			}
			oldAccount.setRemark(account.getRemark());
			oldAccount.setCreateDate(oldAccount.getCreateDate());
			oldAccount.setUpdateDate(new Date());
			oldAccount.setPhone(account.getPhone());
			this.accountDao.update(oldAccount);
		}
	}
	
	/**
	 * 给账号赋予角�?
	 */
	public void grantRole(Long accountID,Long roleID){
		this.accountDao.grantRole(accountID,roleID);
	}
}
